package org.huzhp.gateway.dynamic.rule;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource;
import com.alibaba.csp.sentinel.datasource.Converter;
import org.huzhp.gateway.dynamic.ConsoleProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Description: rule 数据源
 * @Author: huzp
 * @CreateDate: 2020/3/20 11:12
 * @Version: 1.0
 */
public class ConsoleRuleDataSource<T> extends AutoRefreshDataSource<String, T> {


    private static final Logger logger = LoggerFactory.getLogger(ConsoleRuleDataSource.class);

    private ConsoleProperties consoleProperties;

    private RestTemplate restTemplate;

    public ConsoleRuleDataSource(ConsoleProperties consoleProperties, RestTemplate restTemplate, Converter configParser) {
        super(configParser, 30000L);
        this.consoleProperties = consoleProperties;
        this.restTemplate = restTemplate;
    }

    public ConsoleRuleDataSource(Converter configParser, long recommendRefreshMs) {
        super(configParser, recommendRefreshMs);
    }


    @Override
    public String readSource() throws Exception {
        if (consoleProperties.getRule() != null && consoleProperties.getRule().isEnable()) {
            logger.debug("load console gateway rules");
            try {
                GatewayFlowRule[] rules = restTemplate.getForObject(consoleProperties.buildRulePath(), GatewayFlowRule[].class);
                boolean isLoad = GatewayRuleManager.loadRules(Arrays.stream(rules).collect(Collectors.toSet()));
                if (isLoad) {
                    logger.debug("load console gateway rules success");
                }
            } catch (RestClientException e) {
                logger.error("load console gateway rules error");
            }
        }
        return null;
    }
}
